<?php

namespace app\modules\admin\models;

use Yii;
use yii\db\ActiveRecord;

class User extends ActiveRecord implements \yii\web\IdentityInterface
{
    // public $id;
    // public $username;
    // public $password;
    // public $authKey;
    // public $accessToken;

    public static function tableName()
    {
        return 'admin';
    }

    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username'], 'unique'],
            [['username'], 'string', 'max' => 255],
            [['password'], 'string', 'max' => 255],
            [['authKey'], 'string', 'max' => 255],
            [['accessToken'], 'string', 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'username' => '用户名',
            'password' => '密码',
            'authKey' => 'AuthKey',
            'accessToken' => 'AccessToken',
        ];
    }

    // 通过 id 查找用户
    public static function findIdentity($id)
    {
        $user = self::findOne($id);
		return isset($user) ? new static($user) : null;
    }

    // 通过 accesstoken 查找用户
    public static function findIdentityByAccessToken($token, $type = null)
    {
        $user = self::findOne(['accessToken' => $token]);
		return isset($user) ? new static($user) : null;
    }

    // 通过 username 查找用户
    public static function findByUsername($username)
    {
        $user = self::findOne(['username' => $username]);
		return isset($user) ? new static($user) : null;
    }

    // 返回用户 id
    public function getId()
    {
        return $this->id;
    }

    // 返回用户 authKey
    public function getAuthKey()
    {
        return $this->authKey;
    }

    // 验证 authKey
    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    // 验证 password
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password);
    }

    // 生成基于Yii安全组件的加密密码
    public function generatePassword($password)
    {
        $this->password = Yii::$app->security->generatePasswordHash($password);
    }

    // 生成基于Yii安全组件的随机码authKey
    public function generateAuthKey()
    {
        $this->authKey = Yii::$app->security->generateRandomString();
    }

    // 生成基于Yii安全组件的随机码accessToken
    public function generateAccessToken()
    {
        $this->accessToken = Yii::$app->security->generateRandomString();
    }
}
